package net.kodra.gwt.crx.demo.client;

import com.google.gwt.chrome.crx.client.Console;
import com.google.gwt.chrome.crx.client.Extension;
import com.google.gwt.chrome.crx.client.Tabs;
import com.google.gwt.chrome.crx.client.Tabs.Tab;
import com.google.gwt.chrome.crx.client.events.BrowserActionEvent;
import com.google.gwt.chrome.crx.client.events.TabUpdatedEvent;
import com.google.gwt.chrome.crx.client.events.TabUpdatedEvent.ChangeInfo;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.ClosingEvent;

/**
 * The Chrome extension background page script.
**/
@Extension.ManifestInfo(
    name = "DemoExtension (by me)",
    description = "Chrome Extension generated with GWT.",
    version = "0.1.0.2",
    permissions = {"tabs", "http://*/*", "https://*/*"},
    icons = {"resources/demo_16.png", "resources/demo_32.png", "resources/demo_48.png", "resources/demo_128.png"},
    publicKey = "")
public class DemoExtension extends Extension
{

  private final MyBrowserAction browserAction = GWT.create(MyBrowserAction.class);
  private final MyBrowserActionEventListener myBrowserActionEventListener = new MyBrowserActionEventListener();

  @Override
  public String getVersion()
  {
    return "0.1.0.1";
  }

  @Override
  public void onBackgroundPageLoad()
  {
    //Console.log(this.getClass().getName() + ".onBackgroundPageLoad(): here we go");
    log(this.getClass().getName() + ".onBackgroundPageLoad(): here we go");
    // Register page action and browser action listeners.
    browserAction.addListener(myBrowserActionEventListener);

    Tabs.getOnUpdatedEvent().addListener(new TabUpdatedEvent.Listener()
    {
      public void onTabUpdated(int tabId, ChangeInfo changeInfo, Tab tab)
      {
        if (changeInfo.getStatus().equals(ChangeInfo.STATUS_LOADING))
        {
          log("onTabUpdated(): tabId=" + tabId + ", tab=" + tab);
        }
      }
    });

  }

  /**
   * Listener that is responsible for handling clicks on the browser action icon.
   */
  private class MyBrowserActionEventListener implements BrowserActionEvent.Listener
  {
    @Override
    public void onClicked(Tab tab)
    {
      int tabId = tab.getId();
      String tabUrl = tab.getUrl();
      log(this.getClass().getName() + ".onClicked(): " + tab);

    }
  }

  /**
   * Write a debug message to the JavaScript console.
   */
  public final native void log(String logMessage) /*-{
    console.log(logMessage);
  }-*/;


}
